package com.cy.shiro;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.Permission;

public class UrlPermission implements Permission{

    private String url;
    private String method;

    public UrlPermission(String url) {
        this(url, "GET");
    }

    public UrlPermission(String url, String method) {
        this.url = url;
        this.method = method.toUpperCase();
    }

    @Override
    public boolean implies(Permission p) {
        if (!(p instanceof UrlPermission)) {
            return false;
        }

        UrlPermission up = (UrlPermission) p;
        if (method.equals(up.getMethod())){
            String pattern = url;
            if (StringUtils.endsWith(url, "*")){
                pattern = url.replaceFirst("\\*", ".*");
            }
            return up.getUrl().matches(pattern);
        }
        return false;
    }

    public String getUrl() {
        return url;
    }

    public String getMethod() {
        return method;
    }
}